package logger

import (
	"fmt"
	"path/filepath"
	"strings"
	"time"

	rotatelogs "github.com/lestrrat-go/file-rotatelogs"

	coreConfig "bestcore/config"

	"github.com/gofiber/fiber/v2"
	fiberLogger "github.com/gofiber/fiber/v2/middleware/logger"
)

type Config struct {
	Name          string        // 日志名
	RotationCount uint          // 日志最大保存天数
	MaxAge        time.Duration // 日志最大保存时间
	RotationTime  time.Duration // 日志切割时间
}

var logger *rotatelogs.RotateLogs

func Get() *rotatelogs.RotateLogs {
	return logger
}

var middleware func(*fiber.Ctx) error

func GetMiddleWare() func(*fiber.Ctx) error {
	return middleware
}
func Init(config *Config) error {
	var err error
	logger, err = rotatelogs.New(
		filepath.Join(coreConfig.Get().WorkPath, "logs", "%Y%m%d.%H%M."+config.Name+".log"),
		rotatelogs.WithLinkName(filepath.Join(coreConfig.Get().WorkPath, "logs", config.Name+".log")),
		rotatelogs.WithMaxAge(config.MaxAge),               //clear 最小分钟为单位
		rotatelogs.WithRotationCount(config.RotationCount), //number 默认7份 大于7份 或到了清理时间 开始清理
		rotatelogs.WithRotationTime(config.RotationTime),   //rotate 最小为1分钟轮询。默认60s  低于1分钟就按1分钟来
	)
	if err != nil {
		return err
	} else {
		middleware = fiberLogger.New(fiberLogger.Config{
			Format: strings.Join([]string{
				"============[${time}]============",
				"url     : ${url}",
				"reqbody : ${body}",
				"latency : ${latency}",
				"method  : ${method}",
				"status  : ${status}",
				"resbody : ${resBody}",
				"",
			}, "\n"),
			Output: logger,
		})
		fmt.Println("logger config load success")
		return nil
	}
}
